package com.thinkgem.jeesite.modules.quartz;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.MetricsReader;
import com.thinkgem.jeesite.common.utils.MetricsReader.Headers;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.us.entity.UsAttendanceAdp;
import com.thinkgem.jeesite.modules.us.service.UsAttendanceAdpService;

@Service("fileProcessJob")
public class FileProcessJob {

	// 原始目录
	public final String adpSrcDirName = Global.getUserfilesBaseDir()
			+ Global.getConfig("adpSrcDirName");
	// 中转目录
	public final String adpTransferDirName = Global.getUserfilesBaseDir()
			+ Global.getConfig("adpTransferDirName");
	// 中转目录,真是存放文件地址
	public final String adpTransferDirName2 = Global.getUserfilesBaseDir()
			+ Global.getConfig("adpTransferDirName2");
	// 备份目录
	public final String adpBackupsDirName = Global.getUserfilesBaseDir()
			+ Global.getConfig("adpBackupsDirName");
	/**
	 * 日志
	 */
	private static final Log log = LogFactory.getLog(FileProcessJob.class);

	 @Autowired
	 private UsAttendanceAdpService usAttendanceAdpService;

	/**
	 * 定时任务拷贝及处理文件.
	 */
	public void doSomeThing() {
		try {

			// copy文件到指定中专目录
			boolean result = FileUtils.copyDirectoryCover(adpSrcDirName,
					adpTransferDirName, true);
			if (result) {
				// 删除上传过的原文件
				FileUtils.deleteDirectory2(adpSrcDirName);
			} else {
				return;
			}

			// 解析文件，把数据放到数据库
			// 列出源目录下的所有文件名和子目录名
			File srcDir = new File(adpTransferDirName2);
			File[] files = srcDir.listFiles();
			if (files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].isFile()) {
						String fileName = files[i].getAbsolutePath();
						// 如果是一个单个文件，则直接复制
						importFile(fileName);
						String newFileName = adpBackupsDirName
								+ files[i].getName();
						// 拷贝文件
						boolean flag = FileUtils.copyFileCover(fileName,
								newFileName, true);
						if (flag) {
							// 删除原始文件
							FileUtils.deleteFile(fileName);
						}
					}
				}
			}
			log.info("测试定时任务..............................");
			System.out.println("测试定时任务..............................");
		} catch (Exception e) {
			log.error("美国正岗定时任务拷贝及处理文件错误" + e.getMessage(), e);
			e.printStackTrace();
		}

	}

	/**
	 * 数据库保存数据 TODO Add comments here.
	 * 
	 * 解析CSV格式
	 * 
	 * @param fileName
	 */
	public void importFile(String fileName) {
		int successNum = 0;
		int failureNum = 0;
		try {

			MetricsReader metricsReader = new MetricsReader();
			Reader in = new FileReader(fileName);
			Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader(
					Headers.class).parse(in);
			UsAttendanceAdp adp = null;
			for (CSVRecord record : records) {
				adp = new UsAttendanceAdp();
				adp.setCompanyCode(record.get(0));
				adp.setEmployeeId(record.get(1));
				adp.setLastName(record.get(2));
				adp.setPayrollId(record.get(3));	
				adp.setSupervisor(record.get(4));			
				adp.setPayCycles(record.get(5));		
				adp.setOutType(record.get(6));	
				adp.setWorkedDepartment(record.get(7));	
				adp.setState(record.get(8));
				SimpleDateFormat sdf = new SimpleDateFormat(
						"MM/dd/yyyy HH:mm:ss", Locale.US);
				Date date = sdf.parse(record.get(9));
				adp.setInTime(date);
				SimpleDateFormat sdfOut = new SimpleDateFormat(
						"MM/dd/yyyy HH:mm:ss", Locale.US);
				Date dateOut = sdfOut.parse(record.get(10));
				adp.setOutTime(dateOut);		
				adp.setOutPunchType(record.get(11));	
				adp.setHours(record.get(12));		
				adp.setEarningsCode(record.get(13));		
				adp.setNotes(record.get(14));
				// 保存
				 usAttendanceAdpService.save(adp);
				successNum++;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			failureNum++;
			log.error("美国正岗定时解析文件错误" + e.getMessage(), e);
			e.printStackTrace();
		}
	}

	/**
	 * 数据库保存数据 TODO Add comments here. 解析XML格式
	 * 
	 * @param fileName
	 */
	public void importFile2(String fileName) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(fileName, 1, 0);
			UsAttendanceAdp adp = null;
			for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
				try {
					Row row = ei.getRow(i);
					adp = new UsAttendanceAdp();
					for (int j = 0; j < ei.getLastCellNum(); j++) {
						Object val = ei.getCellValue(row, j);
						switch (j) {
						case 0:
							adp.setCompanyCode(String.valueOf(val));
							break;
						case 1:
							adp.setEmployeeId(String.valueOf(val));
							break;
						case 2:
							adp.setLastName(String.valueOf(val));
							break;
						case 3:
							adp.setPayrollId(String.valueOf(val));
							break;
						case 4:
							adp.setSupervisor(String.valueOf(val));
							break;
						case 5:
							adp.setPayCycles(String.valueOf(val));
							break;
						case 6:
							adp.setOutType(String.valueOf(val));
							break;
						case 7:
							adp.setWorkedDepartment(String.valueOf(val));
							break;
						case 8:
							adp.setState(String.valueOf(val));
							break;
						case 9:
							SimpleDateFormat sdf = new SimpleDateFormat(
									"MM/dd/yyyy HH:mm:ss", Locale.US);
							Date date = sdf.parse(String.valueOf(val));
							adp.setInTime(date);
							break;
						case 10:
							SimpleDateFormat sdfOut = new SimpleDateFormat(
									"MM/dd/yyyy HH:mm:ss", Locale.US);
							Date dateOut = sdfOut.parse(String.valueOf(val));
							adp.setOutTime(dateOut);
							break;
						case 11:
							adp.setOutPunchType(String.valueOf(val));
							break;
						case 12:
							adp.setHours(String.valueOf(val));
							break;
						case 13:
							adp.setEarningsCode(String.valueOf(val));
							break;
						default:
							adp.setNotes(String.valueOf(val));
							break;
						}
					}
					// 保存
					// usAttendanceAdpService.save(adp);
					successNum++;
				} catch (Exception e) {
					// TODO: handle exception
					failureNum++;
					log.error("美国正岗定时解析文件错误" + e.getMessage(), e);
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("美国正岗定时解析文件错误" + e.getMessage(), e);
		}
	}
}
